package cn.edu.hizee.gps.controller;

import cn.edu.hizee.gps.dao.DeviceRepository;
import cn.edu.hizee.gps.dao.UserDeviceRepository;
import cn.edu.hizee.gps.model.Device;
import cn.edu.hizee.gps.model.UserDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author ZX
 */
@RequestMapping("device")
@RestController
public class DeviceController extends BaseController {

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private UserDeviceRepository userDeviceRepository;

    /**
     * 绑定设备
     * @param deviceNumber
     * @param userId
     * @param response
     * @return
     */
    @RequestMapping(value = "add_device")
    public String addDevice(String deviceNumber, Integer userId, HttpServletResponse response){
        Device device = deviceRepository.findByDeviceNumber(deviceNumber);
        if(device == null){
            if(deviceRepository.save(new Device(deviceNumber, null, null)) != null){
                UserDevice userDevice = new UserDevice(userId,deviceRepository.findByDeviceNumber(deviceNumber).getId(),null,null,null);
                userDeviceRepository.save(userDevice);
                return ajaxReturn(response, 1, "success", null);
            }
            return ajaxReturn(response, 0, "false", null);
        }else {
            return ajaxReturn(response, 0, "请不要重复绑定", null);
        }
    }
}
